package com.zhongjian.technologycal.mall.fragment;

import android.content.Intent;

import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.activity.LoginActivity;
import com.zhongjian.technologycal.mall.activity.main.activity.ProductsDetailsActivity;
import com.zhongjian.technologycal.mall.activity.shoppingcart.activity.ConfirmNewCartOrderActivity;
import com.zhongjian.technologycal.mall.activity.shoppingcart.bean.ProductListBean;
import com.zhongjian.technologycal.mall.adapter.ShoppingCartAdapter;
import com.zhongjian.technologycal.mall.base.BaseFragment;
import com.zhongjian.technologycal.mall.bean.BaseBean;
import com.zhongjian.technologycal.mall.bean.CartBean;
import com.zhongjian.technologycal.mall.bean.ShoppingCartBean;
import com.zhongjian.technologycal.mall.bean.TestBean;
import com.zhongjian.technologycal.mall.net.HttpRetrofitClient;
import com.zhongjian.technologycal.mall.utils.LoadingDialog;
import com.zhongjian.technologycal.mall.utils.LoadingTip;
import com.zhongjian.technologycal.mall.utils.NetWorkUtils;
import com.zhongjian.technologycal.mall.utils.StatusBarUtil;
import com.zhongjian.technologycal.mall.utils.ToastUitl;
import com.zhongjian.technologycal.mall.utils.UserUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import rx.Subscriber;

/**
 * Created by wei on 2018/1/22.
 * 购物车的实现
 */
public class ShoppingCartFragment extends BaseFragment implements ShoppingCartAdapter.ModifyCountInterface, ShoppingCartAdapter.CheckInterface {
    @BindView(R.id.iv_back_page)
    ImageView iv_back_page;
    @BindView(R.id.tv_main_title)
    TextView tv_maiin_title;
    @BindView(R.id.loadedTip)
    LoadingTip loadingTip;
    @BindView(R.id.cart_total_tv_money)
    TextView cart_total_tv_money;

    @BindView(R.id.cart_RefreshLayout)
    RefreshLayout cart_RefreshLayout;
    @BindView(R.id.expandableListView)
    ExpandableListView listView;
    @BindView(R.id.all_checkBox)
    CheckBox allCheckBox;
    //false就是编辑，ture就是完成
    private ShoppingCartAdapter adapter;
    private ArrayList<CartBean> listItems = new ArrayList<>();
    List<List<ProductListBean>> goods = new ArrayList<>();
    private android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    };


    @Override
    protected void initView() {
        StatusBarCompat.setStatusBarColor(getActivity(), getResources().getColor(R.color.border_color), true);
        Intent intent = new Intent();
        if (UserUtils.getUserToken() == null || UserUtils.getUserToken().equals("")) {
            intent.setClass(getActivity(), LoginActivity.class);
            startActivity(intent);
        } else {
            initRequest();
        }
        cart_RefreshLayout.setEnableLoadmore(false);
        tv_maiin_title.setText("购物车");
        iv_back_page.setVisibility(View.INVISIBLE);
        cart_RefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                cart_RefreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initRequest();
                        cart_RefreshLayout.finishRefresh();
                        cart_total_tv_money.setText("¥ " + 0.00);
                        if (allCheckBox.isChecked()) {
                            allCheckBox.setChecked(false);
                        }
                    }
                }, 1000);
            }
        });
    }

    @Override
    public void initPresenter() {
        initRequest();
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_shopping_cart;
    }

    /**
     * 购物车数据请求
     */
    private void initRequest() {
        if (!NetWorkUtils.isNetConnected(getActivity())) {
            loadingTip.setLoadingTip(LoadingTip.LoadStatus.error);
            return;
        } else {
            HttpRetrofitClient.getInstance(getActivity()).getUrlRequestCartList(UserUtils.getUserToken(), new Subscriber<ResponseBody>() {
                @Override
                public void onStart() {
                    super.onStart();
                    loadingTip.setLoadingTip(LoadingTip.LoadStatus.loading);
                }

                @Override
                public void onCompleted() {
                    if (listItems.size() <= 0) {
                        loadingTip.setLoadingTip(LoadingTip.LoadStatus.noShopping);
                    }
                }

                @Override
                public void onError(Throwable e) {
                    loadingTip.setLoadingTip(LoadingTip.LoadStatus.sereverError);
                }

                @Override
                public void onNext(ResponseBody responseBody) {
                    loadingTip.setLoadingTip(LoadingTip.LoadStatus.finish);
                    try {
                        Gson gson = new Gson();
                        JSONObject jsonObject = new JSONObject(responseBody.string());
                        if (jsonObject.optInt("error_code") == 0) {
                            JSONArray jsonArray = jsonObject.optJSONArray("data");
                            List<CartBean> forlist = gson.fromJson(jsonArray.toString(), new TypeToken<List<CartBean>>() {
                            }.getType());
                            setData(forlist);
                            initEvents();
                        } else if (jsonObject.optInt("error_code") == 3) {
                            Intent intent = new Intent();
                            intent.setAction("com.broadcast.info_out_line");
                            getActivity().sendBroadcast(intent);
                        } else {
                            ToastUitl.showShort(jsonObject.optString("error_message"));
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

        }

    }

    private void setData(List<CartBean> foreshowList) {
        if (listItems != null) {
            listItems.clear();
        }
        for (CartBean vo : foreshowList) {
            listItems.add(vo);
        }
        handler.sendEmptyMessage(0);
    }

    /**
     * 初始化ExpandableListView
     */
    private void initEvents() {
        adapter = new ShoppingCartAdapter(getActivity(), listItems);
        adapter.setCheckInterface(this);// 关键步骤1,设置复选框接口
        adapter.setModifyCountInterface(this);// 关键步骤2,设置数量增减接口
        listView.setAdapter(adapter);
        for (int i = 0; i < adapter.getGroupCount(); i++) {
            listView.expandGroup(i);// 关键步骤3,初始化时，将ExpandableListView以展开的方式呈现
        }
        adapter.notifyDataSetChanged();
        listView.setGroupIndicator(null);

        listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition, long l) {
                Intent intentOther = new Intent();
                intentOther.setClass(getActivity(), ProductsDetailsActivity.class);
                intentOther.putExtra("productId", String.valueOf(listItems.get(groupPosition).getProductList().get(childPosition).getProduct().getId()));
                startActivity(intentOther);
                return true;
            }
        });
    }


    /**
     * //删除购物车数据
     *
     * @param groupPosition
     * @param childPosition
     */
    @Override
    public void childDelete(int groupPosition, int childPosition) {
        requestDelCart(listItems.get(groupPosition).getProductList().get(childPosition).getId(), groupPosition, childPosition);
    }

    /**
     * 选中父
     *
     * @param groupPosition 组元素位置
     * @param isChecked     组元素选中与否
     */
    @Override
    public void checkGroup(int groupPosition, boolean isChecked) {
        CartBean group = listItems.get(groupPosition);
        for (int i = 0; i < group.getProductList().size(); i++) {
            group.getProductList().get(i).setChoosed(isChecked);
        }
        if (isCheckAll()) {
            allCheckBox.setChecked(true);//全选
        } else {
            allCheckBox.setChecked(false);//反选
        }
        adapter.notifyDataSetChanged();
        calculate();

    }

    /**
     * ∑∑∑∂∂∂∂∂∂∂
     *
     * @param groupPosition 组元素位置
     * @param childPosition 子元素位置
     * @param isChecked     子元素选中与否
     */
    @Override
    public void checkChild(int groupPosition, int childPosition, boolean isChecked) {
        boolean allChildSameState = true; //判断该组下面的所有子元素是否处于同一状态
        CartBean group = listItems.get(groupPosition);
        for (int i = 0; i < group.getProductList().size(); i++) {
            //不选全中
            if (group.getProductList().get(i).isChoosed() != isChecked) {
                allChildSameState = false;
                break;
            }
        }
        if (allChildSameState) {
            group.setChoose(isChecked);//如果子元素状态相同，那么对应的组元素也设置成这一种的同一状态
        } else {
            group.setChoose(false);//否则一律视为未选中
        }
        /**
         *
         */
        if (isCheckAll()) {
            allCheckBox.setChecked(true);//全选
        } else {
            allCheckBox.setChecked(false);//反选
        }
        adapter.notifyDataSetChanged();
        calculate();

    }


    /**
     * 增加商品数量
     *
     * @param groupPosition 组元素位置
     * @param childPosition 子元素位置
     * @param showCountView 用于展示变化后数量的View
     * @param isChecked     子元素选中与否
     */
    @Override
    public void doIncrease(int groupPosition, int childPosition, View showCountView, boolean isChecked) {
        ProductListBean cartInfo = listItems.get(groupPosition).getProductList().get(childPosition);
        int currentCount = cartInfo.getProductnum();
        currentCount++;
        requestEditCart(listItems.get(groupPosition).getProductList().get(childPosition).getId(),
                cartInfo,
                currentCount,
                showCountView);

    }

    /**
     * 减少商品数量
     *
     * @param groupPosition 组元素位置
     * @param childPosition 子元素位置
     * @param showCountView 用于展示变化后数量的View
     * @param isChecked     子元素选中与否
     */
    @Override
    public void doDecrease(int groupPosition, int childPosition, View showCountView, boolean isChecked) {
        ProductListBean cartInfo = listItems.get(groupPosition).getProductList().get(childPosition);
        int currentCount = cartInfo.getProductnum();
        if (currentCount == 1)
            return;
        currentCount--;
        requestEditCart(listItems.get(groupPosition).getProductList().get(childPosition).getId(),
                cartInfo,
                currentCount,
                showCountView);

    }

    /**
     * 编辑购物车
     */
    private void requestEditCart(int cartId, final ProductListBean cartInfo, final int buynum, final View showCountView) {
        if (!NetWorkUtils.isNetConnected(getActivity())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getActivity())
                .postUrlRequestUpdateCartInfoNum(cartId, UserUtils.getUserToken(), buynum, new Subscriber<ResponseBody>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        LoadingDialog.showDialogForLoading(getActivity());
                    }

                    @Override
                    public void onCompleted() {
                        LoadingDialog.cancelDialogForLoading();

                    }

                    @Override
                    public void onError(Throwable e) {
                        LoadingDialog.cancelDialogForLoading();
                        ToastUitl.showShort(e.getMessage());

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        LoadingDialog.cancelDialogForLoading();
                        try {
                            Gson gson = new Gson();
                            BaseBean baseBean = gson.fromJson(responseBody.string(), BaseBean.class);
                            if (baseBean.getError_code() == 0) {
                                cartInfo.setProductnum(buynum);
                                ((TextView) showCountView).setText(buynum + "");
                                adapter.notifyDataSetChanged();
                            } else {
                                ToastUitl.showShort(baseBean.getError_message());
                            }

                            calculate();

                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }
                });


    }

    /**
     * 删除购物车数据
     *
     * @param cartId
     * @param groupPosition
     * @param childPosition
     */
    private void requestDelCart(int cartId, final int groupPosition, final int childPosition) {
        if (!NetWorkUtils.isNetConnected(getActivity())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getActivity())
                .postUrlRequestDelShoppingInfo(UserUtils.getUserToken(), cartId, new Subscriber<ResponseBody>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        LoadingDialog.showDialogForLoading(getActivity());
                    }

                    @Override
                    public void onCompleted() {
                        LoadingDialog.cancelDialogForLoading();

                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUitl.showShort(e.getMessage());

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        LoadingDialog.cancelDialogForLoading();
                        try {
                            Gson gson = new Gson();
                            BaseBean baseBean = gson.fromJson(responseBody.string(), BaseBean.class);
                            if (baseBean.getError_code() == 0) {
                                ToastUitl.showShort(baseBean.getError_message());
                                List<ProductListBean> product = listItems.get(groupPosition).getProductList();
                                product.remove(childPosition);
                                if (product.size() == 0) {
                                    listItems.remove(groupPosition);
                                }
                                adapter.notifyDataSetChanged();
                            } else {
                                ToastUitl.showShort(baseBean.getError_message());
                            }
                            calculate();

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });

    }

    /**
     * 统计操作<br>
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作<br>
     * 3.给底部的textView进行数据填充
     */
    private void calculate() {
        double total = 0.00;
        java.text.DecimalFormat df = new java.text.DecimalFormat("#0.00");
        for (int i = 0; i < listItems.size(); i++) {
            for (int j = 0; j < listItems.get(i).getProductList().size(); j++) {
                if (listItems.get(i).getProductList().get(j).isChoosed()) {
                    double price1 = listItems.get(i).getProductList().get(j).getProductSpec().getPrice();
                    int count1 = listItems.get(i).getProductList().get(j).getProductnum();
                    if (listItems.get(i).getProductList().get(j).isChoosed()) {
                        double p1 = price1 * count1;
                        total += p1;
                    }

                }
            }
        }
        cart_total_tv_money.setText("¥ " + df.format(total));
    }

    /**
     * 全选和反选
     * 错误标记：
     */
    private void isAllCheck() {
        for (int i = 0; i < listItems.size(); i++) {
            CartBean group = listItems.get(i);
            group.setChoose(allCheckBox.isChecked());
            List<ProductListBean> childs = group.getProductList();
            for (int j = 0; j < childs.size(); j++) {
                childs.get(j).setChoosed(allCheckBox.isChecked());//这里出现过错误
            }
        }
        adapter.notifyDataSetChanged();
        calculate();
    }

    /**
     * @return 判断组元素是否全选
     */
    private boolean isCheckAll() {
        for (CartBean group : listItems) {
            if (!group.isChoose()) {
                return false;
            }
        }
        return true;
    }

    /**
     *
     * @param view
     */
    @OnClick({R.id.all_checkBox, R.id.tv_introduce_commit})
    public void onClick(View view) {
        switch (view.getId()) {
            //全选/与反选
            case R.id.all_checkBox:
                if (UserUtils.getUserToken() == null || UserUtils.getUserToken().equals("")) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), LoginActivity.class);
                    startActivity(intent);
                }else{
                    isAllCheck();
                }

                break;
            //购物车结算
            case R.id.tv_introduce_commit:
                int count = 0;
                String shopName = "";
                for (int i = 0; i < listItems.size(); i++) {
                    List<ProductListBean> list = new ArrayList<>();
                    for (int j = 0; j < listItems.get(i).getProductList().size(); j++) {
                        if (listItems.get(i).getProductList().get(j).isChoosed()) {
                            count++;
                            list.add(listItems.get(i).getProductList().get(j));
                            shopName = listItems.get(i).getProducerName();
                        }
                    }
                    goods.add(list);
                }

                if (UserUtils.getUserToken() == null || UserUtils.getUserToken().equals("")) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), LoginActivity.class);
                    startActivity(intent);
                } else {
                    if (count > 0) {
                        if (goods != null) {
                            Intent intent = new Intent(getActivity(), ConfirmNewCartOrderActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("goodsInfo", (Serializable) goods);
                            intent.putExtras(bundle);
                            intent.putExtra("shopName", shopName);
                            startActivity(intent);
                        }

                    } else {
                        ToastUitl.showShort("亲!请先选择商品哦！");
                    }
                }

                break;

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (goods.size() > 0) {
            goods.clear();
        }
        initRequest();
        cart_total_tv_money.setText("¥ " + 0.00);
        if (allCheckBox.isChecked()) {
            allCheckBox.setChecked(false);
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        adapter = null;
        listItems.clear();
    }
}

